<template>
  <div style="width: 100vw; height: 100vh; overflow: hidden">
    <div class="snackgame">
      贪吃蛇小游戏<span style="font-size: 1rem"
        >(按任意键开始游戏,WASD为控制方向)</span
      >
    </div>

    <div class="game-container" tabindex="0" @keydown="handleKeydown">
      <canvas ref="gameCanvas"></canvas>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { showConfirmDialog } from "vant";

const canvas = ref(null);
const ctx = ref(null);
let snake = [];
let food = {};
let gameInterval;
let direction = "RIGHT";
let isPaused = true; // 添加游戏暂停变量

function initGame() {
  canvas.value = document.querySelector("canvas");
  ctx.value = canvas.value.getContext("2d");
  canvas.value.width = window.innerWidth;
  canvas.value.height = window.innerHeight;

  snake = [{ x: 10, y: 10 }];
  placeFood();

  // 不要立即启动游戏循环
}

function placeFood() {
  food = {
    x: Math.floor(Math.random() * (canvas.value.width / 20)),
    y: Math.floor(Math.random() * (canvas.value.height / 20)),
  };
}

function gameLoop() {
  if (isPaused) return; // 如果游戏暂停，则不执行任何逻辑

  ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
  draw();
  move();

  if (checkCollision()) {
    clearInterval(gameInterval);
    showConfirmDialog({
      message: "Game Over!",
      theme: "round-button",
      confirmButtonText: "再来一局",
      cancelButtonText: "退出游戏",
    })
      .then(() => {
        initGame();
        isPaused = true; // 重置游戏时暂停游戏
        document.querySelector(".game-container").focus();
      })
      .catch(() => {
        // 退出游戏逻辑
      });
  }
}

function draw() {
  snake.forEach((part) => {
    ctx.value.fillStyle = "green";
    ctx.value.fillRect(part.x * 20, part.y * 20, 20, 20);
  });

  ctx.value.fillStyle = "red";
  ctx.value.fillRect(food.x * 20, food.y * 20, 20, 20);
}

function move() {
  const head = { ...snake[0] };

  switch (direction) {
    case "UP":
      head.y--;
      break;
    case "DOWN":
      head.y++;
      break;
    case "LEFT":
      head.x--;
      break;
    case "RIGHT":
      head.x++;
      break;
  }

  snake.unshift(head);

  if (head.x === food.x && head.y === food.y) {
    placeFood();
  } else {
    snake.pop();
  }
}

function checkCollision() {
  const head = snake[0];
  return (
    head.x < 0 ||
    head.x >= canvas.value.width / 20 ||
    head.y < 0 ||
    head.y >= canvas.value.height / 20 ||
    snake.slice(1).some((part) => part.x === head.x && part.y === head.y)
  );
}

const handleKeydown = (event) => {
  document.querySelector(".game-container").focus();

  // 检查游戏是否暂停，如果是，则启动游戏循环
  if (isPaused) {
    gameInterval = setInterval(gameLoop, 150);
    isPaused = false;
  }

  if (event.key === "w" && direction !== "DOWN") direction = "UP";
  if (event.key === "s" && direction !== "UP") direction = "DOWN";
  if (event.key === "a" && direction !== "RIGHT") direction = "LEFT";
  if (event.key === "d" && direction !== "LEFT") direction = "RIGHT";
};

onMounted(() => {
  initGame();
  document.querySelector(".game-container").focus();
});

onUnmounted(() => {
  clearInterval(gameInterval);
});
</script>

<style>
.game-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 90vh;
  margin: 0;
  outline: none; /* Remove outline for better UX */
}
canvas {
  background-color: #f0f0f0;
  display: block;
}

.snackgame {
  background-color: #4caf50; /* 绿色背景 */
  color: white; /* 白色文本 */
  font-size: 24px; /* 字体大小 */
  height: 50px;
  font-family: "Arial", sans-serif; /* 字体家族 */
  text-align: center; /* 文本居中 */
  padding: 10px 0; /* 上下内边距 */
  margin-bottom: 20px; /* 下外边距，与游戏容器分隔 */
  border-radius: 5px; /* 圆角边框 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 阴影效果 */
}
</style>